package com.moxiao.yfjh.module.activity.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.common.util.date.DateUtils;
import com.moxiao.yfjh.framework.ip.core.utils.AreaUtils;
import com.moxiao.yfjh.module.activity.common.GenActiveNoCommonUtil;
import com.moxiao.yfjh.module.activity.common.NoCommonUtil;
import com.moxiao.yfjh.module.activity.controller.admin.activityEnroll.vo.*;
import com.moxiao.yfjh.module.activity.controller.admin.activityInfo.vo.ActivityInfoCreateReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityInfo.vo.ActivityInfoPageReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityInfo.vo.ActivityInfoRespVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityInfo.vo.ActivityInfoUpdateReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityPackage.vo.ActivityPackageCreateReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityPackage.vo.ActivityPackageExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityPackage.vo.ActivityPackageRespVO;
import com.moxiao.yfjh.module.activity.controller.admin.activityenrollverificate.vo.ActivityEnrollVerificateExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchanType.vo.MerchantTypeExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoPageReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.merchantInfo.vo.MerchantInfoRespVO;
import com.moxiao.yfjh.module.activity.controller.admin.packageType.vo.PackageTypeExportReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.productInfo.vo.ProductInfoPageReqVO;
import com.moxiao.yfjh.module.activity.controller.admin.productInfo.vo.ProductInfoRespVO;
import com.moxiao.yfjh.module.activity.controller.admin.productType.vo.ProductTypeExportReqVO;
import com.moxiao.yfjh.module.activity.controller.app.vo.ActivityMemberVO;
import com.moxiao.yfjh.module.activity.controller.app.vo.AppVerificationMeltVo;
import com.moxiao.yfjh.module.activity.convert.activityEnroll.ActivityEnrollConvert;
import com.moxiao.yfjh.module.activity.convert.activityInfo.ActivityInfoConvert;
import com.moxiao.yfjh.module.activity.convert.activityPackage.ActivityPackageConvert;
import com.moxiao.yfjh.module.activity.convert.merchantInfo.MerchantInfoConvert;
import com.moxiao.yfjh.module.activity.convert.productInfo.ProductInfoConvert;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityEnroll.ActivityEnrollDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityInfo.ActivityInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityPackage.ActivityPackageDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.activityenrollverificate.ActivityEnrollVerificateDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.merchanType.MerchantTypeDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.merchantInfo.MerchantInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.packageType.PackageTypeDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.productInfo.ProductInfoDO;
import com.moxiao.yfjh.module.activity.dal.dataobject.productType.ProductTypeDO;
import com.moxiao.yfjh.module.activity.service.activityEnroll.ActivityEnrollService;
import com.moxiao.yfjh.module.activity.service.activityInfo.ActivityInfoService;
import com.moxiao.yfjh.module.activity.service.activityPackage.ActivityPackageService;
import com.moxiao.yfjh.module.activity.service.activityenrollverificate.ActivityEnrollVerificateService;
import com.moxiao.yfjh.module.activity.service.merchanType.MerchantTypeService;
import com.moxiao.yfjh.module.activity.service.merchantInfo.MerchantInfoService;
import com.moxiao.yfjh.module.activity.service.packageType.PackageTypeService;
import com.moxiao.yfjh.module.activity.service.productInfo.ProductInfoService;
import com.moxiao.yfjh.module.activity.service.productType.ProductTypeService;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.privilege.MemberPrivilegeDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.privilege.MemberPrivilegeService;
import com.moxiao.yfjh.module.order.tradeRefund.TradeRefundApiDTO;
import com.moxiao.yfjh.module.order.tradeRefund.TradeRefundApiService;
import com.moxiao.yfjh.module.pay.controller.admin.order.vo.PayOrderSubmitRespVO;
import com.moxiao.yfjh.module.pay.service.order.PayOrderService;
import com.moxiao.yfjh.module.system.dal.dataobject.dict.DictDataDO;
import com.moxiao.yfjh.module.system.service.dict.DictDataService;
import com.moxiao.yfjh.module.system.sms.utils.GreenScanUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.moxiao.yfjh.framework.common.pojo.CommonResult.error;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "app - 相亲活动信息")
@RestController
@RequestMapping("/activity/info")
@Validated
@Log4j2
public class AppActivityInfoController {

    @Resource
    private ActivityInfoService infoService;

    @Resource
    private MerchantInfoService merchantInfoService;

    @Resource
    private ProductInfoService productInfoService;
    @Resource
    private GenActiveNoCommonUtil genActiveNoCommonUtil;

    @Resource
    private PackageTypeService packageTypeService;

    @Resource
    private MerchantTypeService merchantTypeService;

    @Resource
    private ActivityEnrollService enrollService;

    @Resource
    private ActivityPackageService activityPackageService;

    @Resource
    private ProductTypeService productTypeService;

    @Resource
    private BlindMemberUserService blindMemberUserService;
    @Resource
    private ActivityEnrollVerificateService enrollVerificateService;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private GreenScanUtils greenScanUtils;
    @Resource
    private MemberPrivilegeService privilegeService;
    @Resource
    private TradeRefundApiService tradeRefundApiService;
    /**
     * 延迟队列名称
     */
    private String delayQueueName = "delayQueue";
    /**
     * 活动来源常量
     */
    public static final String ACTIVE_SOURCE = "0";

    @Resource
    private PayOrderService payOrderService;

    @GetMapping("/getPackageType")
    @Operation(summary = "获得相亲套餐类型列表")
    public CommonResult<List<PackageTypeDO>> getPackageType() {
        return success(packageTypeService.getPackageTypeList(new PackageTypeExportReqVO()));
    }

    public static <T> String parseListToStr(List<T> list) {
        return list.stream().map(String::valueOf).collect(Collectors.joining(","));
    }

    @PostMapping("/createInfo")
    @Operation(summary = "创建相亲活动信息")
    public CommonResult<Object> createInfo(@Valid @RequestBody ActivityInfoCreateReqVO createReqVO) {
//        todo 是否是会员
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(getLoginUserId());
        if (Objects.isNull(memberUser)) {
            return error(401, "获取个人信息失败");
        }
        //敏感词校验
        try {
            if (StringUtils.isNotEmpty(createReqVO.getName())) {
                Map map = greenScanUtils.greeTextScan(createReqVO.getName());
                if (MapUtils.isNotEmpty(map)) {
                    if (Objects.equals(map.get("suggestion"), "pass")) {
                        log.info("活动名称审核通过!");
                    } else {
                        return error(500, "活动创建失败!活动名称中存在违规信息");
                    }
                }
            }
            if (StringUtils.isNotEmpty(createReqVO.getActiveDesc())) {
                Map map = greenScanUtils.greeTextScan(createReqVO.getName());
                if (MapUtils.isNotEmpty(map)) {
                    if (Objects.equals(map.get("suggestion"), "pass")) {
                        log.info("活动描述审核通过!");
                    } else {
                        return error(500, "活动创建失败!活动描述中存在违规信息");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (StringUtils.isEmpty(memberUser.getIdNumber())) {
            return CommonResult.error(101, "请先实名认证");
        }

        if (1 != memberUser.getHaveMember()) {
            return error(100, "请先成为会员。");
        }

        MemberPrivilegeDO memberPrivilege = new MemberPrivilegeDO();
        int num = infoService.getActivityNum(getLoginUserId(), DateUtils.getMonthFirstDay(), DateUtils.getMonthLastDay());
        // 普通会员
        if (memberUser.getHaveMember() == 1) {
            //TODO 查看当前用户的创建活动次数
            memberPrivilege = privilegeService.getMemberPrivilege(4L);
        } else if (memberUser.getHaveMember() == 2) {
            //TODO 查看当前用户的创建活动次数
            memberPrivilege = privilegeService.getMemberPrivilege(14L);
        }
        if (Objects.nonNull(memberPrivilege)) {
            if (Objects.equals(memberPrivilege.getHavaUnlimited(), (byte) 0)
                    && Objects.equals(memberPrivilege.getStatus(), (byte) 1)) {
                int privilegeNum = Integer.parseInt(memberPrivilege.getPrivilegeNum());
                if (num > privilegeNum) {
                    return error(500, "您本月可创建活动的次数已达到上限！");
                }
            }
        }
        if (StringUtils.isEmpty(createReqVO.getActiveCover())) {
            createReqVO.setActiveCover(memberUser.getAvatar());
        }

        if (StringUtils.isNotEmpty(createReqVO.getActiveNum())) {
            if (createReqVO.getActiveNum().equals("-1")) {
                createReqVO.setMenNum(String.valueOf(-1));
                createReqVO.setWomenNum(String.valueOf(-1));
            } else {
                createReqVO.setMenNum(createReqVO.getActiveNum());
                createReqVO.setWomenNum(createReqVO.getActiveNum());
            }
        }
        createReqVO.setActiveSource("0");
        // 1.创建活动，活动状态是为缴费
        /*****
         * TODO 活动状态流程变更，活动创建需要先缴费在审核，因此流程步骤更由原先的审核→缴费，变更为缴费→审核
         *  2024年04月16日
         */
        createReqVO.setStatus((byte) 1);
        createReqVO.setHeadSex(memberUser.getSex());
        // 活动金额
        BigDecimal amount = new BigDecimal("0.00");
        // 1.1 区分自定义活动和正常活动
        if (createReqVO.getType() == 1) {
            List<ActivityPackageCreateReqVO> activityPackageCreateReqVOS = createReqVO.getPackageProductRespVOList();
            if (CollectionUtils.isEmpty(activityPackageCreateReqVOS)) {
                return error(500, "活动商品信息不能为空");
            }
            List<Long> collect = activityPackageCreateReqVOS.stream().map(ActivityPackageCreateReqVO::getProductType).collect(Collectors.toList());
            String s = parseListToStr(collect);
            createReqVO.setProductType(s);
            amount = new BigDecimal(createReqVO.getActiveCost());
            createReqVO.setMark((byte) 1);
        } else {
            // 自定义活动 价格 9.9
            amount = new BigDecimal("9.9");

            createReqVO.setActiveCost("9.9");

            createReqVO.setMark((byte) 2);
        }
        // 活动的报名截止时间和活动时间以及活动结束时间
        if (createReqVO.getDatetime().length > 0) {
            for (int i = 0; i < createReqVO.getDatetime().length; i++) {
                if (i == 0) {
                    createReqVO.setDeadline(createReqVO.getDatetime()[i]);
                    createReqVO.setActiveDate(createReqVO.getDatetime()[i]);
                } else {
                    createReqVO.setActiveTimeEnd(createReqVO.getDatetime()[i]);
                }
            }
        }
        genActiveNoCommonUtil.addActiveNo(createReqVO);
        Long id = infoService.createCommonInfo(createReqVO);
        // 2.为活动发起者创建报名信息
        ActivityEnrollCreateReqVO enrolReq = new ActivityEnrollCreateReqVO();
        enrolReq.setActivityId(id);
        enrolReq.setNo("EN_" + NoCommonUtil.dateTime() + "_" + NoCommonUtil.getRandom());
        // 2.1 报名未缴费
        enrolReq.setStatus((byte) 1);
        // 正常活动
        if (createReqVO.getType() == 1) {
            //1.2 活动：发起者缴费 活动的缴费金额：根据分佣分摊类型 2= 发起人全款
            if (createReqVO.getCostShare().equals((byte) 2)) {
                int r_num = Integer.parseInt(createReqVO.getMenNum()) + Integer.parseInt(createReqVO.getWomenNum());
                BigDecimal intToBigDecimal = new BigDecimal(r_num);
                // 使用 BigDecimal 的乘法方法进行计算
                BigDecimal result = intToBigDecimal.multiply(amount);
                enrolReq.setPayAmount(result);
            } else {
                enrolReq.setPayAmount(amount);
            }
        } else {// 自定义活动
            enrolReq.setPayAmount(amount);
        }
        enrolReq.setActivityStatus((byte) 0);
        enrolReq.setUserId(getLoginUserId());
        enrolReq.setSex(memberUser.getSex());
        if (createReqVO.getPayway() == 1) {
            enrolReq.setPayType((byte) 1);
        } else {
            enrolReq.setPayType((byte) 2);
        }
        ActivityEnrollDO enroll = enrollService.createAppEnroll(enrolReq);
        Object jsonObject = new Object();
        if (createReqVO.getDeviceType() == 1) {
            if (Objects.nonNull(enroll)) {
                log.info("活动报名缴费-{}", id);
                // 3.为创建者发起报名缴费
                PayOrderSubmitRespVO respVO = enrollService.createPayOrder(enroll.getId());
                // 4.根据支付类型，返回支付串，微信转对象，支付宝直接转String
                Gson gson = new Gson();
                if (createReqVO.getPayway() == 1) {
                    jsonObject = gson.fromJson(respVO.getDisplayContent(), Object.class);
                } else {
                    jsonObject = respVO.getDisplayContent();
                }
                return success(jsonObject);
            }
        } else {
            // ios 直接成功，并修改状态
            enrollService.updatePayStatus(enroll.getId(), (byte) 0);
        }
        return success(jsonObject);
    }

    /**
     * 活动缴费
     *
     * @param id
     * @return
     */
    @PostMapping("/InfoPayment")
    @Operation(summary = "活动缴费")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<Object> createInfo(@RequestParam("id") Long id) {
        ActivityInfoDO infoDO = infoService.getInfo(id);
        if (Objects.nonNull(infoDO)) {
            ActivityEnrollDO enrollDO = enrollService.getSelectOne(infoDO.getId(), infoDO.getHeadUserId(), (byte) -1);
            if (Objects.nonNull(enrollDO)) {
                log.info("发起活动报名缴费-{}", id);
                // 1.为创建者发起报名缴费
                PayOrderSubmitRespVO respVO = enrollService.createPayOrder(enrollDO.getId());
                // 2.根据支付类型，返回支付串，微信转对象，支付宝直接转String
                Gson gson = new Gson();
                Object jsonObject;
                if (enrollDO.getPayType() == 1) {
                    jsonObject = gson.fromJson(respVO.getDisplayContent(), Object.class);
                } else {
                    jsonObject = respVO.getDisplayContent();
                }
                return success(jsonObject);
            } else {
                return error(500, "活动缴费失败！请重新活动缴费");
            }
        } else {
            return error(500, "活动缴费失败！请重新活动缴费");
        }
    }


    @PutMapping("/updateInfo")
    @Operation(summary = "更新相亲活动信息")
    public CommonResult<Boolean> updateInfo(@Valid @RequestBody ActivityInfoUpdateReqVO updateReqVO) {
        infoService.updateInfo(updateReqVO);
        activityPackageService.updatePackage(updateReqVO.getPackageProductRespVOList());
        return success(true);
    }

    @DeleteMapping("/deleteInfo")
    @Operation(summary = "删除相亲活动信息")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteInfo(@RequestParam("id") Long id) {
        infoService.deleteInfo(id);
        return success(true);
    }


    @GetMapping("/getProductTypeList")
    @Operation(summary = "获得相亲商品类型列表")
    public CommonResult<List<ProductTypeDO>> getProductTypeList() {
        return success(productTypeService.getProductTypeList(new ProductTypeExportReqVO()));
    }

    @GetMapping("/getInfo")
    @Operation(summary = "获得相亲活动信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<ActivityInfoRespVO> getInfo(@RequestParam("id") Long id) {

//         个人活动返回活动发起者的信息
        ActivityInfoDO info = infoService.getInfo(id);
        ActivityInfoRespVO activityInfoRespVO = ActivityInfoConvert.INSTANCE.convert(info);
        if (Objects.nonNull(activityInfoRespVO)) {
            // 活动商品
            ActivityPackageExportReqVO exportReqVO = new ActivityPackageExportReqVO();
            exportReqVO.setActiveId(id);
            List<ActivityPackageDO> activityPackageDOS = activityPackageService.getPackageList(exportReqVO);
            List<ActivityPackageRespVO> activityPackageRespVOS = ActivityPackageConvert.INSTANCE.convertList(activityPackageDOS);
            if (CollectionUtils.isNotEmpty(activityPackageRespVOS)) {
                activityPackageRespVOS.forEach(packageProductRespVO -> {
                    Long merchantId = packageProductRespVO.getMerchantId();
                    MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(merchantId);
                    if (Objects.nonNull(merchantInfo)) {
                        packageProductRespVO.setMerchantName(merchantInfo.getName());
                        packageProductRespVO.setAddress(merchantInfo.getAddress());
                    }
                    Long productId = packageProductRespVO.getProductId();
                    ProductInfoDO productInfo = productInfoService.getProductInfo(productId);
                    if (Objects.nonNull(productInfo)) {
                        packageProductRespVO.setProductName(productInfo.getName());
                        packageProductRespVO.setProductIntroduct(productInfo.getProductIntroduct());
                    }
                    Long productType = productInfo.getProductType();
                    ProductTypeDO productTypeDO = productTypeService.getProductType(productType);
                    if (Objects.nonNull(productTypeDO)) {
                        packageProductRespVO.setProductTypeName(productTypeDO.getName());
                    }

                });
                activityInfoRespVO.setPackageProductRespVOList(activityPackageRespVOS);
            }
            //todo 商品类型名称
            String productType = activityInfoRespVO.getProductType();
            if (Objects.nonNull(productType)) {
                String[] templateIdlist = productType.split(",");
                List<Long> idList = Arrays.stream(templateIdlist)
                        .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                List<ProductTypeDO> productTypeList = productTypeService.getProductTypeList(idList);
                List<String> collect = productTypeList.stream().map(ProductTypeDO::getName).collect(Collectors.toList());
                String s = parseListToStr(collect);
                activityInfoRespVO.setProductTypeName(s);
            }
            // 活动创建人是否实名
            if (activityInfoRespVO.getHeadUserId() != null) {
                BlindMemberUserDO memberUserDO = blindMemberUserService.getMemberUser(activityInfoRespVO.getHeadUserId());
                if (Objects.nonNull(memberUserDO)) {
                    if (StringUtils.isNotBlank(memberUserDO.getIdNumber())) {
                        activityInfoRespVO.setHaveNameAuth(1);
                    } else {
                        activityInfoRespVO.setHaveNameAuth(0);
                    }
                }
            }
            if (StringUtils.isNotBlank(activityInfoRespVO.getDeadline())) {
                boolean is_date = NoCommonUtil.isDateTime(activityInfoRespVO.getDeadline());
                if (!is_date) {
                    String formattedDate = NoCommonUtil.getToDate(activityInfoRespVO.getDeadline());
                    activityInfoRespVO.setDeadline(formattedDate);
                }
            }
            //TODO 获得已报名活动人员的数量
            // 男人
            int registeredMenNum = enrollService.getNumber(info.getId(), (byte) 1, null);
            activityInfoRespVO.setRegisteredMenNum(registeredMenNum);
            // 女人
            int registeredWomenNum = enrollService.getNumber(info.getId(), (byte) 2, null);
            activityInfoRespVO.setRegisteredWomenNum(registeredWomenNum);
            //TODO 获得已被选择参加活动人员的数量
            // 男人
            int activityMenNum = enrollService.getNumber(info.getId(), (byte) 1, (byte) 0);
            activityInfoRespVO.setActivityMenNum(activityMenNum);
            // 女人
            int activityWomenNum = enrollService.getNumber(info.getId(), (byte) 2, (byte) 0);
            activityInfoRespVO.setActivityWomenNum(activityWomenNum);
            //TODO 如果是1V1的活动可报名人数的上限为10人
            if (activityInfoRespVO.getMenNum().equals("1") && activityInfoRespVO.getWomenNum().equals("1")) {
                activityInfoRespVO.setRegistrationAvailable(10);
            } else {
                // 男女可报名人数
                Integer num = enrollService.getEnrollNum() / 2;
                activityInfoRespVO.setRegistrationAvailable(num);
            }
            //TODO 验证是否已报名
            Integer enrollNum = enrollService.enrollNum(activityInfoRespVO.getId(), getLoginUserId());
            if (enrollNum > 0) {
                activityInfoRespVO.setIsEnroll(true);
            } else {
                activityInfoRespVO.setIsEnroll(false);
            }
            //TODO 活动：发起者缴费 活动的缴费金额：根据分佣分摊类型 2= 发起人全款
            //将0.00元为单位格式的金额转为分
            int fenAmount = info.getActiveCost().multiply(new BigDecimal(100)).intValue();
            if (activityInfoRespVO.getActiveSource().equals("0") && activityInfoRespVO.getCostShare() == 2) {
                int r_num = Integer.parseInt(info.getMenNum()) + Integer.parseInt(info.getWomenNum());
                int am = fenAmount * r_num;
                // 将分转成0.00元为单位
                BigDecimal newYuanAmount = new BigDecimal(am).divide(new BigDecimal(100));
                String resultString = newYuanAmount.toString();
                activityInfoRespVO.setPayAmount(resultString);
            } else {
                activityInfoRespVO.setPayAmount(activityInfoRespVO.getActiveCost());
            }

            // 是否是发起者
            if (Objects.equals(activityInfoRespVO.getHeadUserId(), getLoginUserId())) {
                activityInfoRespVO.setIsInitiator(true);
            } else {
                activityInfoRespVO.setIsInitiator(false);
            }
            //todo 报名人的头像列表
            ActivityEnrollExportReqVO activityEnrollReqVO = new ActivityEnrollExportReqVO();
            activityEnrollReqVO.setActivityId(activityInfoRespVO.getId());
            activityEnrollReqVO.setStatus((byte) 0);
            activityEnrollReqVO.setActivityStatus((byte) 0);
            List<ActivityEnrollDO> activityEnrollDOS = enrollService.getEnrollList(activityEnrollReqVO);
            if (CollectionUtils.isNotEmpty(activityEnrollDOS)) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                List<Long> userIds = activityEnrollDOS.stream().map(ActivityEnrollDO::getUserId).collect(Collectors.toList());
                List<BlindMemberUserDO> memberUserList = blindMemberUserService.getMemberUserList(userIds);
                if (Objects.nonNull(memberUserList)) {
                    memberUserList.stream().forEach(memberUser -> {
                        JSONObject jsonObject = new JSONObject();
                        //               放入头像
                        jsonObject.put("avatar", memberUser.getAvatar());
//                        放入性别
                        jsonObject.put("sex", memberUser.getSex());
//                        放入是否被选中
                        ActivityEnrollDO activityEnrollDO = activityEnrollDOS.stream().filter(s -> s.getUserId().equals(memberUser.getId())).findFirst().orElse(null);
                        if (Objects.nonNull(activityEnrollDO)) {
                            jsonObject.put("activityStatus", activityEnrollDO.getActivityStatus());
                        }
                        jsonObjectList.add(jsonObject);
                    });
                    activityInfoRespVO.setEnrollAvatarAgeSelectedList(jsonObjectList);
                }
                List<String> avatarList = memberUserList.stream().map(BlindMemberUserDO::getAvatar).collect(Collectors.toList());
                activityInfoRespVO.setAvatarList(avatarList);
            }

            if (activityInfoRespVO.getCostShare() != null) {
                //        todo 获取费用分摊类型
                String costShareName = dictDataService.getDictData("cost_share", String.valueOf(activityInfoRespVO.getCostShare())).getLabel();
                activityInfoRespVO.setCostShareName(costShareName);
            }

//            判断活动是否是个人活动
            if (activityInfoRespVO.getActiveSource().equals("0")) {
                activityInfoRespVO.setActivityMemberVO(setActivityMemberHeaderInfo(activityInfoRespVO.getHeadUserId()));
            }
            activityInfoRespVO.setStatusName(parseStatusName(activityInfoRespVO.getStatus()));
            //TODO 增加核销记录
            ActivityEnrollVerificateExportReqVO verificateExportReqVO = new ActivityEnrollVerificateExportReqVO();
            verificateExportReqVO.setActivityId(activityInfoRespVO.getId());
            verificateExportReqVO.setUserId(getLoginUserId());
            verificateExportReqVO.setStatus((byte) 1);
            List<ActivityEnrollVerificateDO> verificateList = enrollVerificateService.getEnrollVerificateList(verificateExportReqVO);
            if (!verificateList.isEmpty()) {
                List<AppVerificationMeltVo> verificRecordsList = verificateList.stream().map(item -> {
                    AppVerificationMeltVo appVerificationMeltVo = new AppVerificationMeltVo();
                    appVerificationMeltVo.setVTime(DateUtils.getDataToString(item.getVerificationTime()));
                    appVerificationMeltVo.setVerificationCode(item.getVerificationCode());
                    ProductInfoDO productInfoDO = productInfoService.getProductInfo(item.getActivityProductsId());
                    if (Objects.nonNull(productInfoDO)) {
                        appVerificationMeltVo.setProductName(productInfoDO.getName());
                        MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(productInfoDO.getMerchantId());

                        if (Objects.nonNull(merchantInfo)) {
                            appVerificationMeltVo.setMerchantName(merchantInfo.getName());
                        }
                    }
                    return appVerificationMeltVo;
                }).collect(Collectors.toList());
                activityInfoRespVO.setVerificRecordsList(verificRecordsList);
            }
        }
        //  合并活动状态
        activityInfoRespVO.setAppStatus(getAppStatus(activityInfoRespVO.getStatus()));
        activityInfoRespVO.setAppStatusName(parseStatusName(activityInfoRespVO.getAppStatus()));
        return success(activityInfoRespVO);
    }

    private String parseStatusName(Byte status) {
        //0 未审核 1 未缴费 2.报名中 3.未开始 4.进行中 5.己结束 6.已驳回 7.已关闭，8.待成立
        switch (status) {
            case (byte) 1:
                return "未缴费";
            case (byte) 2:
                return "报名中";
            case (byte) 3:
                return "未开始";
            case (byte) 4:
                return "进行中";
            case (byte) 5:
                return "己结束";
            case (byte) 6:
                return "已驳回";
            case (byte) 7:
                return "已关闭";
            case (byte) 8:
                return "待成立";
            case (byte) 0:
            default:
                return "未审核";
        }
    }

    @GetMapping("/getMerchantTypeList")
    @Operation(summary = "获得相亲商家类型列表")
    public CommonResult<List<MerchantTypeDO>> getMerchantTypeList() {
        return success(merchantTypeService.getMerchantTypeList(new MerchantTypeExportReqVO()));
    }

    @GetMapping("/getMerchantInfoPage")
    @Operation(summary = "获得相亲商家信息分页")
    public CommonResult<PageResult<MerchantInfoRespVO>> getMerchantInfoPage(@Valid MerchantInfoPageReqVO pageVO) {
        PageResult<MerchantInfoDO> pageResult = merchantInfoService.getMerchantInfoPage(pageVO);
        PageResult<MerchantInfoRespVO> merchantInfoRespVOPageResult = MerchantInfoConvert.INSTANCE.convertPage(pageResult);
        if (Objects.nonNull(merchantInfoRespVOPageResult)) {
            List<MerchantInfoRespVO> list = merchantInfoRespVOPageResult.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(merchantInfoRespVO -> {
                    MerchantTypeDO merchantType = merchantTypeService.getMerchantType(merchantInfoRespVO.getMerchantType());
                    if (Objects.nonNull(merchantType)) {
                        merchantInfoRespVO.setMerchantTypeName(merchantType.getName());
                    }
                });
            }
        }
        return success(merchantInfoRespVOPageResult);
    }


    @GetMapping("/getMerchantInfo")
    @Operation(summary = "获得相亲商家信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<MerchantInfoRespVO> getMerchantInfo(@RequestParam("id") Long id) {

        MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(id);
        if (Objects.isNull(merchantInfo)) {
            return error(401, "获取个人信息失败");
        } else {
            MerchantInfoRespVO merchantInfoRespVO = MerchantInfoConvert.INSTANCE.convert(merchantInfo);
            MerchantTypeDO merchantType = merchantTypeService.getMerchantType(merchantInfo.getMerchantType());
            if (Objects.nonNull(merchantType)) {
                merchantInfoRespVO.setMerchantTypeName(merchantType.getName());
            }
            return success(merchantInfoRespVO);
        }
    }


    @GetMapping("/getInfoPage")
    @Operation(summary = "获得相亲活动信息分页")
    public CommonResult<PageResult<ActivityInfoRespVO>> getInfoPage(@Valid ActivityInfoPageReqVO pageVO) {
//       默认分页
        pageVO.setIsPage(1);
        if (null == pageVO.getIsHeader()) {
            pageVO.setIsHeader(2);
        }
        PageResult<ActivityInfoDO> page = new PageResult<>();
//       IsHeader: 0：参与活动 1：创建活动 3：获取所有活动
        if (1 == pageVO.getIsHeader()) {

            pageVO.setHeadUserId(getLoginUserId());
            List<ActivityInfoDO> pageResult = infoService.getInfoPageList(pageVO);
            List<ActivityInfoDO> pageResultTotal = infoService.getInfoPageList(pageVO.setIsPage(0));
            page.setList(pageResult);
            page.setTotal((long) pageResultTotal.size());
        } else if (0 == pageVO.getIsHeader()) {
            //            获取数据
            pageVO.setHeadUserId(getLoginUserId());
            List<ActivityInfoDO> infoPageByNotHeader = infoService.getInfoPageByNotHeader(pageVO);
            if (Objects.nonNull(infoPageByNotHeader)) {
                //            获取总数
                Integer count = infoService.getInfoPageByNotHeader(pageVO.setIsPage(0)).size();
                page.setList(infoPageByNotHeader);
                page.setTotal(Long.valueOf(count));
            }
        } else {
//            获取所有活动
            if (null == pageVO.getAuditStatus()) {
                pageVO.setAuditStatus((byte) 1);
            }
            page = infoService.getAppInfoPage(pageVO);
        }
        PageResult<ActivityInfoRespVO> pageList = ActivityInfoConvert.INSTANCE.convertPage(page);
        if (Objects.nonNull(pageList)) {
            if (CollectionUtils.isNotEmpty(pageList.getList())) {
                pageList.getList().forEach(item -> {
                    item.setStatusName(parseStatusName(item.getStatus()));
                    //todo 报名人的头像列表
                    ActivityEnrollExportReqVO activityEnrollReqVO = new ActivityEnrollExportReqVO();
                    activityEnrollReqVO.setActivityId(item.getId());
                    activityEnrollReqVO.setStatus((byte) 0);
                    activityEnrollReqVO.setActivityStatus((byte) 0);
                    List<ActivityEnrollDO> activityEnrollDOS = enrollService.getEnrollList(activityEnrollReqVO);
                    if (CollectionUtils.isNotEmpty(activityEnrollDOS)) {
                        List<Long> userIds = activityEnrollDOS.stream().map(ActivityEnrollDO::getUserId).collect(Collectors.toList());
                        List<BlindMemberUserDO> memberUserList = blindMemberUserService.getMemberUserList(userIds);
                        List<String> avatarList = memberUserList.stream().map(BlindMemberUserDO::getAvatar).collect(Collectors.toList());
                        item.setAvatarList(avatarList);
                    }

                    //TODO 获得已被选择参加活动人员的数量
                    // 男人
                    int activityMenNum = enrollService.getNumber(item.getId(), (byte) 1, (byte) 0);
                    item.setActivityMenNum(activityMenNum);
                    // 女人
                    int activityWomenNum = enrollService.getNumber(item.getId(), (byte) 2, (byte) 0);
                    item.setActivityWomenNum(activityWomenNum);
                    //TODO 获得已报名活动人员的数量
                    // 男人
                    int registeredMenNum = enrollService.getNumber(item.getId(), (byte) 1, (byte) 1);
                    item.setRegisteredMenNum(registeredMenNum);
                    // 女人
                    int registeredWomenNum = enrollService.getNumber(item.getId(), (byte) 2, (byte) 1);
                    item.setRegisteredWomenNum(registeredWomenNum);

                    //todo 商品类型名称
                    ActivityPackageExportReqVO exportReqVO = new ActivityPackageExportReqVO();
                    exportReqVO.setActiveId(item.getId());
                    List<ActivityPackageDO> activityPackageDOS = activityPackageService.getPackageList(exportReqVO);
                    List<ActivityPackageRespVO> packageVo = ActivityPackageConvert.INSTANCE.convertList(activityPackageDOS);
                    String str = "";
                    if (CollectionUtils.isNotEmpty(packageVo)) {
                        for (ActivityPackageRespVO packageRespVO : packageVo) {
                            ProductInfoDO productInfo = productInfoService.getProductInfo(packageRespVO.getProductId());
                            ProductTypeDO productTypeDO = productTypeService.getProductType(productInfo.getProductType());
                            String productType = productTypeDO.getName();
                            str += productType + ",";
                        }
                        MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(packageVo.get(0).getMerchantId());
                        if (Objects.nonNull(merchantInfo)) {
                            item.setAddress(merchantInfo.getAddress());
                        }
                    }

                    if (StringUtils.isNotBlank(str)) {
                        item.setProductTypeName(str.substring(0, str.lastIndexOf(",")));
                    }
                    //        todo 获取费用分摊类型
                    if (item.getCostShare() != null) {
                        String costShareName = dictDataService.getDictData("cost_share", String.valueOf(item.getCostShare())).getLabel();
                        item.setCostShareName(costShareName);
                    }
                    //            判断活动是否是个人活动
                    if ("0".equals(item.getActiveSource())) {
                        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(item.getHeadUserId());
                        if (Objects.nonNull(memberUser)) {
                            item.setHeadName(memberUser.getNickname());
                        }
                    }
                    item.setAppStatus(getAppStatus(item.getStatus()));
                    item.setAppStatusName(parseStatusName(item.getAppStatus()));
                });
            }
        }
        return success(pageList);
    }

    //  合并活动状态
    public Integer getAppStatus(Byte status) {
        Integer appStatus = null;
        if (status.equals((byte) 4) || status.equals((byte) 9) || status.equals((byte) 3) || status.equals((byte) 8)) {
            appStatus = 1;
        }
        if (status.equals((byte) 2)) {
            appStatus = 2;
        }
        if (status.equals((byte) 5) || status.equals((byte) 6) || status.equals((byte) 7)) {
            appStatus = 3;
        }
        if (status.equals((byte) 0)) {
            appStatus = 4;
        }
        if (status.equals((byte) 1)) {
            appStatus = 5;
        }
        return appStatus;
    }


    private String parseStatusName(Integer appStatus) {
        // 1 进行中 2.报名中 3.已结束 4.未审核 5.未缴费
        switch (appStatus) {
            case 1:
                return "进行中";
            case 2:
                return "报名中";
            case 3:
                return "已结束";
            case 4:
                return "未审核";
            default:
                return "未缴费";
        }
    }


    @GetMapping("/getEnroll")
    @Operation(summary = "获得相亲报名信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<ActivityEnrollRespVO> getEnroll(@RequestParam("id") Long id) {
        ActivityEnrollDO enroll = enrollService.getEnroll(id);
        return success(ActivityEnrollConvert.INSTANCE.convert(enroll));
    }

    @GetMapping("/getEnrollPage")
    @Operation(summary = "获得相亲报名信息分页")
    public CommonResult<PageResult<ActivityEnrollRespVO>> getEnrollPage(@Valid ActivityEnrollPageReqVO pageVO) {
        PageResult<ActivityEnrollDO> pageResult = enrollService.getEnrollPage(pageVO);
        return success(ActivityEnrollConvert.INSTANCE.convertPage(pageResult));
    }


    @PostMapping("/createEnroll")
    @Operation(summary = "创建相亲报名信息")
    public CommonResult<Long> createEnroll(@Valid @RequestBody ActivityEnrollCreateReqVO createReqVO) {
        return success(enrollService.createEnroll(createReqVO));
    }


    @DeleteMapping("/deleteEnroll")
    @Operation(summary = "取消相亲报名信息")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteEnroll(@RequestParam("id") Long id) {

        enrollService.deleteEnroll(id);
        return success(true);
    }

    /**
     * 发起人选人环节
     *
     * @return
     */
    @GetMapping("/teamUp")
    @Operation(summary = "组队")
    @Parameters({
            @Parameter(name = "activityId", description = "活动id"),
            @Parameter(name = "userId", description = "用户id：当前选择组队的人员（报名人员的userid）", example = "120"),
            @Parameter(name = "enrollId", description = "报名id", example = "120")
    })
    public CommonResult<Boolean> teamUp(@RequestParam(value = "activityId") Long activityId,
                                        @RequestParam(value = "userId") Long userId,
                                        @RequestParam(value = "enrollId") Long enrollId) {
        ActivityInfoDO activityInfo = infoService.getInfo(activityId);

        if (Objects.isNull(activityInfo)) {
            return error(500, "获取活动信息失败");
        }
        //TODO 更新报名信息
        ActivityEnrollUpdateReqVO updateReqVO = new ActivityEnrollUpdateReqVO();
        updateReqVO.setId(enrollId);
        //组队（配对人员id）
        updateReqVO.setPairId(userId);
        updateReqVO.setNo(activityInfo.getNo());
        updateReqVO.setActivityStatus((byte) 0);
        // 已选择
        updateReqVO.setSelected((byte) 1);
        // 已配对/已组队
        updateReqVO.setIsPair((byte) 0);
        enrollService.updateEnroll(updateReqVO);
        //TODO 活动的组队全部完成后，对已报名的用户进行退款
        //TODO 获得已被选择参加活动人员的数量
        // 男人
        int activityMenNum = enrollService.getNumber(activityInfo.getId(), (byte) 1, (byte) 0);
        // 女人
        int activityWomenNum = enrollService.getNumber(activityInfo.getId(), (byte) 2, (byte) 0);
        if (activityMenNum != 0 && activityWomenNum != 0) {
            //组队人员已满，修改活动状态
            if (String.valueOf(activityMenNum).equals(activityInfo.getMenNum())
                    && String.valueOf(activityWomenNum).equals(activityInfo.getWomenNum())) {
                infoService.updateByStatus(activityInfo.getId(), (byte) 3);
                // 根据活动id查询已报名，但是未被选中的人员，执行退费操作
                TradeRefundApiDTO tradeRefundApiDTO = new TradeRefundApiDTO();
                tradeRefundApiDTO.setActivityId(activityInfo.getId());
                tradeRefundApiService.notStarted(tradeRefundApiDTO);
            }
        }

        return success(true);
    }

    @GetMapping("/getProductInfoPage")
    @Operation(summary = "获得相亲商品信息分页")
    public CommonResult<PageResult<ProductInfoRespVO>> getProductInfoPage(@Valid ProductInfoPageReqVO pageVO) {
        PageResult<ProductInfoDO> pageResult = productInfoService.getProductInfoPage(pageVO);
        PageResult<ProductInfoRespVO> voPageResult = ProductInfoConvert.INSTANCE.convertPage(pageResult);
        if (Objects.nonNull(voPageResult)) {
            List<ProductInfoRespVO> list = voPageResult.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(productInfoRespVO -> {
                    productInfoRespVO.setProductId(productInfoRespVO.getId());
                    ProductTypeDO productType = productTypeService.getProductType(productInfoRespVO.getProductType());
                    if (Objects.nonNull(productType)) {
                        productInfoRespVO.setProductTypeName(productType.getName());
                    }
                    MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(productInfoRespVO.getMerchantId());
                    if (Objects.nonNull(merchantInfo)) {
                        productInfoRespVO.setMerchantName(merchantInfo.getName());
                    }
                });
            }
        }
        return success(voPageResult);
    }

    @GetMapping("/getProductInfo")
    @Operation(summary = "获得相亲商品信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<ProductInfoRespVO> getProductInfo(@RequestParam("id") Long id) {
        ProductInfoDO productInfo = productInfoService.getProductInfo(id);
        ProductInfoRespVO productInfoRespVO = ProductInfoConvert.INSTANCE.convert(productInfo);
        productInfoRespVO.setProductId(productInfo.getId());
        ProductTypeDO productType = productTypeService.getProductType(productInfo.getProductType());
        if (Objects.nonNull(productType)) {
            productInfoRespVO.setProductTypeName(productType.getName());
        }
        MerchantInfoDO merchantInfo = merchantInfoService.getMerchantInfo(productInfoRespVO.getMerchantId());

        if (Objects.nonNull(merchantInfo)) {
            productInfoRespVO.setMerchantName(merchantInfo.getName());
            if (StringUtils.isNotEmpty(merchantInfo.getAddress())) {
                productInfoRespVO.setMerchantAddress(merchantInfo.getAddress());
            }
            if (StringUtils.isNotEmpty(merchantInfo.getMerchantCover())) {
                productInfoRespVO.setMerchantCover(merchantInfo.getMerchantCover());
            }
        }

        return success(productInfoRespVO);
    }

    @GetMapping("/pageByUserId")
    @Operation(summary = "获得相亲活动信息分页(发起人或者参与人)")
    @PreAuthorize("@ss.hasPermission('activity:info:query')")
    public CommonResult<?> getInfoPageByUserId(@Valid ActivityInfoPageReqVO pageVO) {
        if (1 == pageVO.getIsHeader()) {
            PageResult<ActivityInfoDO> pageResult = infoService.selectPageByHeaderId(pageVO);
            return success(ActivityInfoConvert.INSTANCE.convertPage(pageResult));
        } else if (2 == pageVO.getIsHeader()) {
//            获取数据
            List<ActivityInfoDO> infoPageByNotHeader = infoService.getInfoPageByNotHeader(pageVO);
            PageResult<ActivityInfoDO> pageResult = new PageResult<>();
            if (Objects.nonNull(infoPageByNotHeader)) {
                // 获取总数
                Integer count = infoService.getInfoActivityInfoNotHeaderSum(new ActivityInfoPageReqVO().setUserId(pageVO.getUserId()));
                pageResult.setList(infoPageByNotHeader);
                pageResult.setTotal(Long.valueOf(count));
            }
            return success(ActivityInfoConvert.INSTANCE.convertPage(pageResult));
        } else {
            return CommonResult.error(602, "请输入正确的编码");
        }
    }


    public ActivityMemberVO setActivityMemberHeaderInfo(Long headUserId) {
        ActivityMemberVO activityMemberVO = new ActivityMemberVO();
        BlindMemberUserDO memberUser = blindMemberUserService.getMemberUser(headUserId);
        if (Objects.nonNull(memberUser)) {
            activityMemberVO.setUserId(headUserId);
            activityMemberVO.setNickname(memberUser.getNickname());
            activityMemberVO.setAge(memberUser.getAge());
            activityMemberVO.setAvatar(memberUser.getAvatar());
            activityMemberVO.setAreaName(AreaUtils.getAreaName(memberUser.getAreaId()));
            activityMemberVO.setHaveReal(memberUser.getHaveReal());
            activityMemberVO.setMonthIncome(memberUser.getMonthIncome());
            activityMemberVO.setPurchasCar(memberUser.getPurchasCar());
            activityMemberVO.setPurchasHouse(memberUser.getPurchasHouse());
            if (StringUtils.isNotEmpty(memberUser.getMonthIncome())) {
                DictDataDO matchIncomeName = dictDataService.getDictData("matchIncome", memberUser.getMonthIncome());
                activityMemberVO.setMatchIncomeName(matchIncomeName.getLabel());
            }
            boolean haveNameAuth = StringUtils.isNotEmpty(memberUser.getName()) && StringUtils.isNotEmpty(memberUser.getIdNumber());
            activityMemberVO.setHaveNameAuth(haveNameAuth ? 1 : 0);
            activityMemberVO.setHaveMember(memberUser.getHaveMember());
            return activityMemberVO;
        }
        return activityMemberVO;
    }

    /**
     * 活动报名人数验证
     *
     * @return
     */
    public void checkingActivityInfo(Long activityId) {
        ActivityInfoDO activityInfoDO = infoService.getInfo(activityId);
        if (Objects.nonNull(activityInfoDO)) {
            // 男生：已报名且已参加活动的人数
            Integer enroll_mem = enrollService.getNumber(activityId, (byte) 1, (byte) 0);
            // 女生：已报名且已参加活动的人数
            Integer enroll_womem = enrollService.getNumber(activityId, (byte) 2, (byte) 0);

            Integer a_menNum = Integer.valueOf(activityInfoDO.getMenNum());
            Integer a_WomenNum = Integer.valueOf(activityInfoDO.getWomenNum());
            // 人数足够后，活动进入到未开始状态
            if (Objects.equals(enroll_mem, a_menNum) && Objects.equals(enroll_womem, a_WomenNum)) {
                infoService.updateByStatus(activityId, (byte) 3);
            }
        }

    }
}
